package com.zh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zh.Exception.AddressBookNONE;
import com.zh.Exception.ShoppingCartNONE;
import com.zh.common.BaseContext;
import com.zh.entity.*;
import com.zh.mapper.OrdersMapper;
import com.zh.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 你爹
 * @since 2023-09-21
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private UserService userService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Transactional
    @Override
    public void submit(Orders orders) throws ShoppingCartNONE, AddressBookNONE {
        //获取下单人ID 昵称
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);
        String userName = user.getName();
        //生成订单号
        long orderId = IdWorker.getId();
        //查询购物车数据 查询收货人地址 昵称 电话
        LambdaQueryWrapper<ShoppingCart> shoppingCartWrapper = new LambdaQueryWrapper<>();
        shoppingCartWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartWrapper);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartNONE();
        }
        //计算订单总金额
        BigDecimal amount = BigDecimal.ZERO;
        for (ShoppingCart shoppingCart : shoppingCartList) {
            System.out.println("amountPart:" + shoppingCart.getAmount().multiply(BigDecimal.valueOf(shoppingCart.getNumber())));
            amount = amount.add(shoppingCart.getAmount().multiply(BigDecimal.valueOf(shoppingCart.getNumber())));
        }
        System.out.println("totalAmount:" + amount);
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        String address = addressBook.getProvinceName()
                + addressBook.getCityName()
                + addressBook.getDistrictName()
                + addressBook.getDetail();
        if (address.equals("")) {
            throw new AddressBookNONE("请填写收货地址");
        }
        String consignee = addressBook.getConsignee();
        String phone = addressBook.getPhone();
        //插入订单表 声明：跳过付款的，所以状态应该直接待派送
        orders.setNumber(String.valueOf(orderId));
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now().plusMinutes(2));
        orders.setStatus(2);
        orders.setAmount(amount);
        orders.setAddress(address);
        orders.setPhone(phone);
        orders.setConsignee(consignee);
        orders.setUserName(userName);
        log.info("end : orders:" + orders);
        this.save(orders);
        //插入订单明细表
        List<OrderDetail> orderDetails = new ArrayList<>();
        //设置orderId dishId/setmealId dishFlavor number amount
        shoppingCartList.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetails.add(orderDetail);
        });
        orderDetailService.saveBatch(orderDetails);
        //清空购物车
        shoppingCartService.remove(new LambdaUpdateWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, userId));
    }

    @Override
    public void setStatus(Orders orders) {
        this.updateById(orders);
    }
}
